import moment from 'moment'

export const fl6 = {
  labelCol: {span: 8},
  wrapperCol: {span: 16},
}
export const fl8 = {
  labelCol: {span: 6},
  wrapperCol: {span: 15},
}
export const fl12 = {
  labelCol: {span: 5},
  wrapperCol: {span: 16},
}

export const fl24 = {
  labelCol: {span: 2},
  wrapperCol: {span: 22},
}

export const findFatherTree = (data, id, indexArr = []) => {
  // 树形json根据子节点的id寻找出其所有父节点
  let arr = Array.from(indexArr)
  for (let i = 0; i < data.length; i++) {
    arr.push({
      name: data[i].name,
      path: data[i].path,
      hidden: data[i].hidden
    })
    if (data[i].path === id) {
      return arr
    }
    let children=data[i].routes
    if (children && children.length) {
      let result = findFatherTree(children, id, arr)
      if (result.length) return result
    }
    arr.pop()
  }
  return []
}

export const formatAuthMenu = (list, authMenu=[]) => {
  // 根据路由自动生成出菜单项
  if (authMenu.indexOf('SUPER_ADMIN') >= 0) {
    return list
  }
  let arr = []
  list.forEach(route => {
    if (route.noAuth) {
      arr.push(route)
    } else {
      if (route.auth) {
        let auth = route.auth||[]
        let is = auth.findIndex(item => {
          // 处理角色对比
          return authMenu.indexOf(item) >=0
        })
        if (is>=0) {
          arr.push(route)
        }
      }else {
        const {routes}=route
        // 使用递归过滤，支持无限极嵌套
        let newArr = formatAuthMenu(routes, authMenu)
        if (newArr.length){
          arr.push({
            ...route,
            routes: newArr
          })
        }
      }
    }
  })
  return arr
};

export const limitWords = (val, num = 30) => {
  // 字数限制，默认30
  if (val && val.length >= num) {
    return `${val.substring(0, num)}...`
  }
  return val
}

export const ftTime = (val, format='YYYY-MM-DD') => {
  // 格式化表单提交时的时间格式
  return val?moment(val).format(format):null
}
export const initMoment = (val) => {
  // 表单组件初始化的时候的init值
  return val?moment(val):null
}


export const companyTreeChange=(data=[], companyId) => {
  // 组织部门树的转换
  function change(v, node) {
    let isCompany= !!v.companyId
    if (isCompany) {
      arr.push({
        id: v.companyId,
        companyId: v.companyId,
        name: v.companyName,
        count: v.userCount,
        node,
        isCompany,
      })
    }else {
      arr.push({
        id: v.departmentId,
        name: v.departmentName,
        companyId,
        count: v.userCount,
        node,
        isCompany,
      })
    }
  }
  let arr =[]
  data.forEach(v => {
    let cid=companyId
    if (!cid){
      cid=v.companyId
    }
    if (v.node&&v.node.length) {
      let node = companyTreeChange(v.node, cid)
      change(v, node)
    }else {
      change(v, undefined, cid)
    }
  })
  return arr
}
